<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\model\ActiveParticipantsModel;
use app\model\ActivitiesModel;
use app\model\UserModel;
use think\App;
use think\facade\Db;

class Activities extends Base {

    private $model;
    private  $activeParticipantsModel;
    private $userModel;
    private $req;
    private $uid;
    private $page;
    private $limit = 20;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page']  : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit']  : 10;

        $this->uid = $this->getUid();

        $this->model = new ActivitiesModel();

        $this->activeParticipantsModel = new ActiveParticipantsModel();

        $this->userModel = new UserModel();
    }



    public function getActiveList(){

        $where = [];
        $where[] = ["is_delete","=",0];
        $where[] = ["active_status","IN",[1,2]];

        $list = $this->model->getList($where,$this->page,$this->limit,["active_status"=>"ASC","stop_time"=>"ASC"]);

        foreach ($list as &$one){
            $one["is_have_sign_up"] = $this->activeParticipantsModel->isHaveSignUp($one["active_id"],$this->uid);
            if( $one["is_have_sign_up"]){
                $one["is_can_sign_up"] = -1;
            }
        }

        $total = $this->model->getTotal($where);

        return $this->succData($total,$list);

    }






    public function getActiveInfo(){

        if(!isset($this->req['active_id']) || empty($this->req['active_id'])){
            return $this->fail("活动Id不能为空");
        }

        $info = $this->model->getInfo($this->req['active_id']);

        if($info){
            $info["is_have_sign_up"] = $this->activeParticipantsModel->isHaveSignUp($this->req['active_id'],$this->uid);
            if( $info["is_have_sign_up"]){
                $info["is_can_sign_up"] = -1;
            }
        }

        return $this->succ($info);
    }


    public function getActiveSignUpList(){

        if(!isset($this->req['active_id']) || empty($this->req['active_id'])){
            return $this->fail("活动Id不能为空");
        }

        $where = [];
        $where["active_id"] = $this->req['active_id'];
        $sign_up_list = $this->activeParticipantsModel->getList($where,$this->page,$this->limit,"created_at","DESC");
        if($sign_up_list){
            foreach ($sign_up_list as &$u){
                $user = $this->userModel->getUserInfoByUid($u["uid"]);
                $u['avatar'] = $user ? $user["avatar"] : "";
            }
        }
        $total = $this->activeParticipantsModel->getTotal($where);


        return $this->succData($total,$sign_up_list);
    }


    /*
     * 获取用户的报名信息
     * */

    public function getJoinActiveInfo(){

        if(!$this->uid){
            return $this->noLogin();
        }

        if(!isset($this->req['active_id']) || empty($this->req['active_id'])){
            return $this->fail("活动Id不能为空");
        }

        $res = $this->activeParticipantsModel->getList([
            "active_id"=>$this->req["active_id"],
            "uid"=>$this->uid,
        ]);


        return $this->succ($res[0]);
    }


    /*
     * 参与活动
     * */
    public function joinActive()
    {

        if(!$this->uid){
            return $this->noLogin();
        }

        if(!isset($this->req['active_id']) || empty($this->req['active_id'])){
            return $this->fail("活动Id不能为空");
        }

        $info = $this->model->getInfo($this->req['active_id']);

        if($info["active_status"]  == -1){
            return $this->fail("活动已下架");
        }

        if($info["active_status"]  == 2){
            return $this->fail("活动已结束");
        }

        if($info["remaining_time"]  <= 0){
            return $this->fail("活动报名已截止");
        }


        $info["is_have_sign_up"] = $this->activeParticipantsModel->isHaveSignUp($this->req['active_id'],$this->uid);
        if( $info["is_have_sign_up"]){
            return $this->fail("已报名，不可重复报名");
        }

        if($info["active_max_num"] != 0 && $info["active_current_num"] >= $info["active_max_num"]){
            return $this->fail("活动报名已满");
        }

        if(empty($this->req["name"]) || mb_strlen($this->req["name"]) > 32){
            return $this->fail("名字不能为空且长度不能大于32位");
        }

        if(empty($this->req["phone"]) || !verification_mobile($this->req["phone"])){
            return $this->fail("手机号不合法");
        }


        Db::startTrans();

        $res1 = $this->activeParticipantsModel->addOne([
            "active_id"=>$this->req["active_id"],
            "uid"=>$this->uid,
            "name"=>$this->req["name"],
            "phone"=>$this->req["phone"],
        ]);

        $res2 = $this->model->incrField($this->req["active_id"],"active_current_num");

        $this->model->delCache($this->req["active_id"]);

        if($res1  && $res2){
            Db::commit();
            return $this->succ();
        }else{
            return $this->fail();
        }

    }



    /*
     * 取消报警
     * */
    public function cancelJoinActive()
    {

        if(!$this->uid){
            return $this->noLogin();
        }

        if(!$this->uid){
            return $this->noLogin();
        }

        if(!isset($this->req['active_id']) || empty($this->req['active_id'])){
            return $this->fail("活动Id不能为空");
        }

        $info = $this->model->getInfo($this->req['active_id']);

        if($info["active_status"]  == -1){
            return $this->fail("活动已下架");
        }

        if($info["active_status"]  == 2){
            return $this->fail("活动已结束");
        }

        $info["is_have_sign_up"] = $this->activeParticipantsModel->isHaveSignUp($this->req['active_id'],$this->uid);
        if(!$info["is_have_sign_up"]){
            return $this->fail("你还未报名,不可完成此操作");
        }


        Db::startTrans();

        $res1 = $this->activeParticipantsModel->where([
            "active_id"=>$this->req["active_id"],
            "uid"=>$this->uid,
        ])->delete();

        $res2 = $this->model->decField($this->req["active_id"],"active_current_num");

        $this->model->delCache($this->req["active_id"]);

        if($res1  && $res2){
            Db::commit();
            return $this->succ();
        }else{
            return $this->fail();
        }

    }


    public function exportActiveSignUpList(){

        if(!request()->isGet()){
            return $this->fail("仅支持GET请求");
        }

        if(!isset($this->req['active_id']) || empty($this->req['active_id'])){
            return $this->fail("活动Id不能为空");
        }

        $info = $this->model->getInfo($this->req['active_id']);

        if(empty($info)){
            return $this->fail("活动不存在");
        }


        $where = [];
        $where["active_id"] = $this->req['active_id'];
        $sign_up_list = $this->activeParticipantsModel->getList($where,null,null,"created_at","DESC");

        $headers=["用户ID","名称","电话","报名时间"];
        $saveList =[];
        foreach ($sign_up_list as $item){
            $save =[];
            $save[] = $item["uid"];
            $save[] = $item["name"];
            $save[] = $item["phone"];
            $save[] = $item["created_at"];
            $saveList[] = $save;
        }

        $fileName = $info["active_name"]."报名表.xlsx";

        exportToExcel($headers,$saveList,$fileName);

        return $this->succ();
    }

}
